package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
)

var (
	addr = flag.String("addr", "127.0.0.1:4000", "服务端地址(ip:port)")
)

func main() {
	// 解析命令行参数
	flag.Parse()

	conn, err := net.Dial("tcp", *addr)
	if err != nil {
		log.Fatalf("could to connect %v", err)
	}
	defer conn.Close()

	// 接受用户输入

	r := bufio.NewReader(os.Stdin)

	go func() {
		for {
			msg, _ := r.ReadBytes('\n')
			conn.Write(msg)
		}
	}()

	// 接受服务器输入
	go func() {
		for {
			buf := make([]byte, 1024)
			n, err := conn.Read(buf)
			if err != nil {
				log.Fatalln(err)
			}
			if n > 0 {
				fmt.Print(string(buf))
			}
		}
	}()

	select {}
}
